import sqlite3
import logging
'''
Created on 8 Jun 2010

@author: A Hopkins
'''

class nmapDatabase():
    '''
    classdocs
    '''


    def __init__(self,dbOutputFile):
        #self.np = np
        self.dbOutputFile = dbOutputFile
        
    def createDatabase(self):
        self.conn = sqlite3.connect(self.dbOutputFile) 
        self.cursor = self.initTables(self.conn)
    
     #creates the databases that will have data stored
    def initTables(self, conn):
        c = self.conn.cursor()
        try:
            c.execute('''CREATE TABLE hosts(ipaddress VARCHAR(15), macaddress CHAR(17), osName VARCHAR(60))''')
            c.execute('''CREATE TABLE services(ipaddress VARCHAR(15), protocol VARCHAR(3), port VARCHAR(5), service VARCHAR(30), confidence VARCHAR(30), product VARCHAR(30), state VARCHAR(30), extrainfo VARCHAR(30), PRIMARY KEY (ipaddress, protocol, port))''')
            c.execute('''CREATE TABLE scriptResults(ipaddress VARCHAR(15), protocol VARCHAR(3), port VARCHAR(5), nmapscriptid varchar(10), scriptoutput VARCHAR(1000), FOREIGN KEY (ipaddress, protocol, port) REFERENCES services(ipaddress, protocol, port))''')
        except sqlite3.OperationalError as strerror:
            logging.error ("SQLITE error - DirectoryParser_initTables: " + str(strerror))  
            sys.exit(2)
        return c
      
    def query(self, query):
        
        if query != "":  
            try:
                conn = sqlite3.connect(self.dbOutputFile) 
                c = conn.cursor()
                c.execute(query)
            except sqlite3.OperationalError as strerror:
                logging.error ("-- SQLITE ERROR - queryDatabase: " + str(strerror))  
        
            for row in c:
                logging.info (row)
        
